#ifdef __QT5_TARGET

#include <QtSql/QSqlQuery>

#else

#include <QSqlQuery>

#endif

#include "FilterManager.h"
#include "CouldNotExecQueryException.h"
#include "CouldNotCastException.h"


FilterManager::FilterManager(void)
{
	this->defaultFilter = NULL;
}

FilterManager::~FilterManager(void)
{
	try{
	if(!name_filter_map.empty())
	{
		QMap<QString,Filter*>::iterator it = this->name_filter_map.begin();
		while(it != this->name_filter_map.end())
		{
			if(it.value() != NULL)
			{
				delete it.value();
				it.value() = NULL;
			}
			it++;
		}
	}
	if(defaultFilter != NULL)
	{
		//delete defaultFilter;
		defaultFilter = NULL;
	}
	}catch(int i)
	{
		Exception e;
		e.setErrorCode(i);
		e.setMessage("Fatal error: memory corruption while deleting the Filter manager");
		throw e;
	}

}

QList<Filter*> FilterManager::getAllFilters()
{
	return this->name_filter_map.values();
}

const Filter* FilterManager::getDefaultFilter()
{
	return this->defaultFilter;
}

void FilterManager::setDefaultFilter(const QString& name)
{
	this->name_filter_map.value(name)->setDefault(true); 
	this->defaultFilter = this->name_filter_map.value(name);
}

int FilterManager::addFilterToDatabase(Filter* filter)
{
	QSqlQuery query;
	query.prepare("insert into filters (patient_id,name,isdefault,fromdate,todate,onlyfirstvisits,onlylastvisits,onlyfollowups) values (filter_seq.nextval(),:patient_id,:name,:isdefault,:fromdate,:todate,:onlyfirstvisits,:onlylastvisits,:onlyfolloups)");
	if(filter->getPatient() == NULL)
		query.bindValue(":patient_id",-1);
	else
		query.bindValue(":patient_id",filter->getPatient()->getFilenr());
	query.bindValue(":name",filter->getName());
	query.bindValue(":isdefault",filter->isDefault());
	query.bindValue(":fromdate",filter->getFrom());
	query.bindValue(":todate",filter->getTo());
	query.bindValue(":onlyfirstvisits",filter->isFirstVisits());
	query.bindValue(":onlylastvisits",filter->isLastVisits());
	query.bindValue(":onlyfollowups", filter->isOnlyFollowUps());
	if(!query.exec())
	{
		CouldNotExecQueryException e;
		e.setMessage("Could not add filter. " + query.lastError().text());
		throw e;
	}
	this->name_filter_map.insert(filter->getName(),filter);
	return 0;
}

void FilterManager::addFilter(Filter* filter)
{
	this->name_filter_map.insert(filter->getName(),filter);
}

QStringList FilterManager::getAllFilterNames()
{
	return this->name_filter_map.keys();
}

const Filter* FilterManager::findFilter(const QString& name)
{
	return this->name_filter_map.value(name);
}